package com.sac.common.aspect;

import com.sac.common.exception.TokenException;
import com.sac.common.service.LogService;
import com.sac.common.utils.HttpContextUtils;
import com.sac.common.utils.TokenUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 
 * @author xiaodong
 * @date 2018年9月25日 下午4:04:28
 * @desc
 */
@Aspect
@Component
public class AuthTokenAspect {
	private static final Logger logger = LoggerFactory.getLogger(AuthTokenAspect.class);

	// 存放鉴权信息的Header名称，默认是Authorization
	private String httpHeaderName = "Authorization";

	// 鉴权失败后返回的错误信息，默认为401 unauthorized
	private String unauthorizedErrorMessage = "401 unauthorized";

	// 鉴权失败后返回的HTTP错误码，默认为401
	private int unauthorizedErrorCode = HttpServletResponse.SC_UNAUTHORIZED;

	/**
	 * 存放登录用户模型Key的Request Key
	 */
	public static final String REQUEST_CURRENT_KEY = "REQUEST_CURRENT_KEY";

	@Autowired
	LogService logService;

	@Pointcut("@annotation(com.sac.common.annotation.AuthToken)")
	public void tokenPointCut() {
		
	}

	/**
	 * 目标方法执行之前调用
	 * @throws IOException
	 */
	@Around("tokenPointCut()")
	public Object doAuthToken(ProceedingJoinPoint point) throws Throwable {
		MethodSignature signature = (MethodSignature) point.getSignature();
		Method method = signature.getMethod();
		String className = point.getTarget().getClass().getName();
		String methodName = signature.getName();
		System.out.println("Restful API:["+className + "." + methodName + "()"+"] Verifying.............");
		HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
		// 获取token
		String token = request.getHeader(httpHeaderName);
		// 验证token
		boolean verify = TokenUtil.verify(token);
		if (verify) {
			System.out.println("Restful API:["+className + "." + methodName + "()"+"] Authenticating successfully");
			Object object = point.proceed(); // 执行连接点目标方法
			return object;
		} else {
			System.out.println("Restful API:["+className + "." + methodName + "()"+"] Authenticating failed");
			throw new TokenException(unauthorizedErrorCode,unauthorizedErrorMessage);
		}
	}
}
